package com.ln.core.security;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.ln.core.security.entity.Users;
import com.ln.core.security.service.UsersService;
import com.ln.core.utils.UserFilter;

public class LoginAuthenticationSuccesssHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler {
	@Autowired
	private UsersService usersService;

	public LoginAuthenticationSuccesssHandler() {
	}

	/**
	 * Constructor which sets the <tt>defaultTargetUrl</tt> property of the base class.
	 * 
	 * @param defaultTargetUrl
	 *            the URL to which the user should be redirected on successful authentication.
	 */
	public LoginAuthenticationSuccesssHandler(String defaultTargetUrl) {
		setDefaultTargetUrl(defaultTargetUrl);
	}

	/**
	 * Calls the parent class {@code handle()} method to forward or redirect to the target URL, and then calls {@code clearAuthenticationAttributes()} to remove any leftover session data.
	 */
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		UserDetails userDetails = (UserDetails) authentication.getPrincipal();
		Users user = usersService.find("account", userDetails.getUsername());

		// 将当前登陆用户设置到loginedUserMap中去
		Map<HttpSession, Users> uMap = new HashMap<HttpSession, Users>();
		uMap.put(request.getSession(), user);
		UserFilter.loginedUserMap.put(user.getId(), uMap);

		request.getSession().setAttribute("USER", user);

		handle(request, response, authentication);
		clearAuthenticationAttributes(request);
	}

	/**
	 * Removes temporary authentication-related data which may have been stored in the session during the authentication process.
	 */
	protected final void clearAuthenticationAttributes(HttpServletRequest request) {
		HttpSession session = request.getSession(false);

		if (session == null) {
			return;
		}

		session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	}

}
